package com.chen.web.servlet;

import com.chen.domain.LoginUser;
import com.chen.domain.User;
import com.chen.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
//登录
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//      获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");

//      验证码验证
        HttpSession session = request.getSession();
        String checkCode_session = (String) session.getAttribute("checkCode_session");
        //验证码只有一次效果，拿来后删除session里的验证码
        request.getSession().removeAttribute("checkCode_session");

//      把把网页参数封装成一个对象javaBean
        LoginUser loginUser = new LoginUser(username,password);
//        去数据库判断是否存在这个用户,如果存在返回用户的信息,如果返回是null说明没有这个用户
//        UserService这个类提供了用户的更种操作
        UserService userService = new UserService();
        User user = userService.login(loginUser);

        if (checkCode_session != null && checkCode_session.equalsIgnoreCase(checkCode)) {
            if(user!=null){
                String role = user.getRole();
                String admin = "admin";
                String user1 = "user";

                session.setAttribute("user", username);
                if(role.equals(admin)){
                    response.sendRedirect(request.getContextPath() + "/admin.jsp");
                }else if(role.equals(user1)){
                    //登录成功展示一个成功的页面
                    //向成功的界面给一个用户名的数据
                    //重定向
                    response.sendRedirect(request.getContextPath() + "/userHome.jsp");
                }
            }else {

                request.setAttribute("login_error","用户名密码错误!!!");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }
        }else {//验证码错误
            request.setAttribute("cc_error","验证码错误!!!");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
